<template>
	<wsPage title="主题编辑">
		<div slot="page_operate">
			<Button  @click="goBack"><Icon type="ios-arrow-back"></Icon><span>返回</span></Button>
		</div>
		<wsPanel>
			<template slot="panel_head_title">编辑主题</template>
			<div slot="panel_body" class="ws-form-div">
				<div class="ws-form-div-form">
					<div class="step-data">
						<Form ref="modalForm" :model="modal.form" :rules="modal.validate" :label-width="100">
					        <FormItem label="名称" prop="name">
					            <Input v-model="modal.form.name" autofocus></Input>
					        </FormItem>
					        <FormItem label="发布区域" prop="position">
					        	<Select  v-model="modal.form.position" placeholder="请选择">
					                <Option :value="index + 1" v-for="(item, index) in fields.types">{{item}}</Option>
					            </Select>
					        </FormItem>
					        <FormItem label="类型" prop="type">
					            <RadioGroup  v-model="modal.form.type">
					                <Radio :label="1">上新</Radio>
					                <Radio :label="2">折扣</Radio>
					            </RadioGroup>
					        </FormItem>
					        <FormItem label="语言" prop="languageCode">
					            <Select  v-model="modal.form.languageCode" placeholder="请选择">
					                <Option :value="item.code" v-for="item in fields.languages">{{item.motherTongue}}|{{item.english}}</Option>
					            </Select>
					        </FormItem>
					        <FormItem label="主题背景" required>
					            <ws-upload-cos
							        ref="upload"
							        catelog="topic"
							        :cfile-key="modal.upload.key"
							        :show-upload-list="false"
							        :format="['jpg','jpeg','png']"
							        :max-size="2048"
							        :on-success="uploadSuccess"
							        type="drag"
							        style="display: inline-block;">
							        <div style="width: 400px;height:200px;margin: 5px;">
							            <img :src="modal.form.imageUrl" v-if="modal.form.imageUrl != ''" width="400px" height="200px" >
							        </div>
							    </ws-upload-cos>
								<div><span>图片规格为1024*988</span></div>
					        </FormItem>
					        <FormItem label="主题详情" required>
					        	<!--主题项目-->
								<wsSmPanel>
									<div slot="list_operate">
										<Button  @click="showAddItemModal">添加主题项</Button>
									</div>
									<div slot="list_data">
										<ws-table :data="modal.table.data" style="width: 100%">
											<ws-table-column type="index" width="50"></ws-table-column>
											<ws-table-column align="center" prop="title" label="标题"></ws-table-column>
											<ws-table-column align="center" label="商品数量" width="100">
												<template slot-scope="scope">
													<a @click="showProducts(scope.$index)">{{scope.row.productNum}}</a>
												</template>
											</ws-table-column>
											<ws-table-column align="center" width="200" label="操作">
												<template slot-scope="scope">
													<Button @click="showQueryProducts(scope.row, scope.$index)" type="text" size="small">设置商品</Button>
													<Button @click="showEditModal(scope.row, scope.$index)" type="text" size="small">编辑</Button>
						        					<Button type="text" size="small" @click="delModalRow(scope.$index)">删除</Button>
						      					</template>
											</ws-table-column>
										</ws-table>
									</div>
								</wsSmPanel>
					        </FormItem>
					         <FormItem>
					         	<Button type="primary" @click="saveForm">保存</Button>
					         	<Button @click="goBack">取消</Button>
					         </FormItem>
					    </Form>	
					</div>
				</div>
			</div>
		</wsPanel>
		
		<wsModal v-model="modalItem.show" :title="modalItem.title" :width="660"  @on-ok="modalSave"  @on-cancel="modalCancel">
			 <wsEditor class="ws-form-select" :defaultMsg="modalItem.form.content" :config="editor.config" ref="ue"></wsEditor>
		</wsModal>	
		
		<wsModal v-model="productModal.show" :title="productModal.title" :width="660"  @on-ok="productModalSave"  @on-cancel="productModalCancel">
			<ws-table :data="productModal.table.data" style="width: 100%">
				<ws-table-column type="index" width="50"></ws-table-column>
				<ws-table-column align="center" prop="title" label="店铺"></ws-table-column>
				<ws-table-column align="center" label="商品名称" >
					<template slot-scope="scope">
						<a>{{scope.row.productNum}}</a>
					</template>
				</ws-table-column>
				<ws-table-column align="center" prop="title" label="价格" width="100"></ws-table-column>
				<ws-table-column align="center" width="100" label="操作">
					<template slot-scope="scope">
    					<Button type="text" size="small" @click="delModalRow(scope.$index)">删除</Button>
  					</template>
				</ws-table-column>
			</ws-table>			 
		</wsModal>
		
		<wsModal v-model="productQueryModal.show" :title="productQueryModal.title" :width="660"  @on-ok="productModalSave"  @on-cancel="productModalCancel">
			<div style="min-height: 600px;">
				<product-query ref="product1"></product-query>
			</div>
		</wsModal>
	</wsPage>
</template>

<script>	
	import Util from '../../../common/util.js'
	import Common from '../../../common/common.js';
	import FileUtil from '../../../common/file.js';
	import productQuery from '../appCategory/productQuery';
	
	export default {
		components: {
    		productQuery
    	},
		data() {
			return {
				//新增属性弹框
				modal: {
					show: false,
					form: {
						id:null,
						name: '',
						type: 1,
						languageCode: null,
						position: 1,
						imageUrl: '',
					},
					upload: {
						key: ''
					},
					validate: {
						name: [
	                        { required: true, message: '名称不能为空', trigger: 'blur' }
	                    ],
	                    languageCode: [
	                        { required: true, message: '请选择语言'}
	                    ],
	                    position: [
	                        { required: true, message: '发布位置必须选择'}
	                    ],
	                    type: [
	                        { required: true, message: '必须选择类型'}
	                    ]
					},
					table: {
						data:[], //主题项记录
						productData: [] //主题项商品记录
					}
				},
				modalItem: {
					show: false,
					editIndex: -1, //当前编辑元素为-1
					title: '新增主题项',
					form: {
						content: ''
					}
				},
				//文本编辑器
				editor: {
            		message: '',
            		config: {
            			initialFrameWidth: 600,
            			initialFrameHeight: 350,
            			zIndex: 11000
            		}
            	},
            	productModal: {
            		show: false,
            		title: '选择商品',
            		table: {
            			data: []
            		}
            	},
            	productQueryModal: {
            		show: false,
            		title: '选择商品'
            	},
            	fields: {
            		languages: [],
            		types: ['轮播主题', '推荐主题', '单图主题', '商品关联主题']
            	}
			}
		},
		computed: {
			isEdit() {
		      return !Util.vad.isBlank(this.modal.form.id);
		    }
		},
		mounted() {
			this.modal.form.id = this.$route.query.topicId;
			this.init();
		},
		methods: {
			init() {
				this.initLanguages();
				this.initTopic();
			},
			/**
			 * 查询主题信息
			 */
			initTopic() {
				let _this = this;
				let topicId = this.modal.form.id;
				this.axios.get('/ws/ops/v2/topics/' + topicId).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.buildTopicInfo(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			/**
			 * 构建主题内容
			 */
			buildTopicInfo(data) {
				this.modal.form.name = data.topic.name;
				this.modal.form.type = data.topic.type;
				this.modal.form.languageCode = data.topic.languageCode;
				this.modal.form.imageUrl = data.topic.imageUrl;
				this.modal.form.position = data.topic.position;
				
				this.modal.table.data = [];
				let items = data.items;
				for(let i = 0; i < items.length; i++) {
					let item = items[i];
					item['title'] = '主题项';
					this.modal.table.data.push(item);
					//商品信息
					this.modal.table.productData.push({});
				}
			},
			/**
			 * 初始化可翻译的语言列表
			 */
			initLanguages() {
				let _this = this;
				this.axios.get('/ws/ops/v2/languages/translatable').then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if (0 == resMeta.code) {
						_this.fields.languages = res.data;
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
            /**
             * 返回
             */
            goBack() {
    			this.$router.push({name: 'ops_topic_list'});
    		},
    		/**
    		 * 显示编辑主题项弹框
    		 */
    		showAddItemModal() {
    			this.modalItem.show = true;
    			this.modalItem.editIndex = -1;
    			this.$refs['ue'].setUEContent('');
    		},
    		/**
    		 * 模态框保存
    		 */
    		modalSave() {
    			if(-1 == this.modalItem.editIndex) {
    				//新增
    				this.submitAddModal();
    			} else {
    				this.submitEditModal();
    			}
    		},
    		/**
    		 * 提交新增的模态框
    		 */
    		submitAddModal() {
    			let content = this.$refs['ue'].getUEContent();
    			if(Util.vad.isBlank(content)) {
    				this.$Message.info('请添加主题内容哦');
    				return;
    			}
    			this.modal.table.data.push({
    				title: '主题项',
    				content: content,
    				productNum: 0
    			});
    			//同时新增一条商品列表记录
    			this.modal.table.productData.push({});
    			this.modalItem.show = false;
    		},
    		/**
    		 * 提交编辑编辑框
    		 */
    		submitEditModal() {
    			let index_ = this.modalItem.editIndex;
    			let content = this.$refs['ue'].getUEContent();
    			this.modal.table.data[index_].content = content;
    			this.modalItem.show = false;
    		},
    		/**
    		 * 模态框取消
    		 */
    		modalCancel() {
    			this.modalItem.show = false;
    		},
    		/**
    		 * 显示编辑框
    		 */
    		showEditModal(row_, index) {
    			this.modalItem.title = '编辑主题项';
    			this.modalItem.editIndex = index;
    			let data_ = this.modal.table.data[index];
//  			this.$refs['ue'].setUEContent(data_.content);
				this.modalItem.form.content = data_.content;
    			this.modalItem.show = true;
    		},
    		delModalRow(index) {
    			this.modal.table.data.splice(index, 1);
    			this.modal.table.productData.splice(index, 1);
    		},
    		/**
    		 * 显示商品
    		 */
    		showProducts(index) {
    			this.productModal.show = true;	
    		},
    		/**
    		 * 商品保存
    		 */
    		productModalSave() {
    			let selections = this.$refs['product1'].getSelections();
    			let index_ = this.modalItem.editIndex;
    			for(item in selections) {
    				let productId = selections[item].productId;
    				if(!this.modal.table.productData[index_][productId]) {
    					this.modal.table.productData[index_][productId] = selections[item];
    				}
    			}
    			console.log(Object.keys(this.modal.table.productData[index_]).length);
    			this.modal.table.data[index_].productNum = Object.keys(this.modal.table.productData[index_]).length;
    			this.productQueryModal.show = false;
    		},
    		/**
    		 * 取消保存商品
    		 */
    		productModalCancel() {
    			this.productQueryModal.show = false;
    		},
    		/**
    		 * 显示商品查询选择
    		 */
    		showQueryProducts(row_, index) {
    			this.productQueryReset();
    			this.modalItem.editIndex = index;
    			this.productQueryModal.show = true;
    		},
    		productQueryReset() {
    			this.$refs['product1'].resetForm();
    		},
    		/**
    		 * 保存表单
    		 */
    		saveForm() {
    			this.$refs['modalForm'].validate((valid) => {
					if (valid) {
						if(this.modal.table.data.length == 0) {
		    				this.$Message.info('必须设置主题内容哦');
		    				return;
		    			}
						if(Util.vad.isBlank(this.modal.form.imageUrl)) {
							this.$Message.info('必须设置主题背景图');
		    				return;
						}
						this.submitForm();
                    } 
               });
    		},
    		submitForm() {
    			//构建数据模型
    			let postData = {};
    			postData.topic = this.modal.form;
    			postData.items = this.modal.table.data;
    			postData.products = [];
    			let products = this.modal.table.productData;
    			for(item in products) {
    				let productArray = [];
    				let productMap = products[item];
    				for(productId in productMap) {
    					productArray.push(productMap[productId]);
    				}
    				postData.products.push(productArray);
    			}
    			
    			let _this = this;
    			
    			this.axios.put('/ws/ops/v2/topic', postData).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('修改主题成功');
						_this.$router.push({name:'ops_topic_list'});
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('修改主题失败:' + message_);
					}
				});
				
    		},
    		uploadSuccess(response, file, fileList) {
				if(0 == response.meta.code) {
					this.modal.form.imageUrl = response.data.pubFileUrl;
					this.modal.upload.key = response.data.fileId;
				}
			}
		}
	}
</script>

<style scoped>

</style>